//
//  XImageCache.m
//  WeiboSpace
//
//  Created by linan4 li on 12-5-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "XImageCache.h"
#import "CommonCrypto/CommonDigest.h"
#import "WBUtil.h"
@interface XImageCache()
-(NSString*)urlToFullPath:(NSString*)url;
@end
@implementation XImageCache

static XImageCache *instance = nil;
+(XImageCache*)shareXImageCache
{
    @synchronized(self)
    {
        if (instance == nil)
        {
            instance = [[XImageCache alloc]init];
        }
    }
    return instance;
}

- (id)init
{
    self = [super init];
    if (self) {
        cacheDic = [[NSMutableDictionary alloc]init];
        
//        //创建docment\\images文件夹
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *documentsDirectory = [paths objectAtIndex:0];
        //创建docment\tmp\images目录
        NSString *documentsDirectory = NSTemporaryDirectory();
        if (documentsDirectory!=nil) {
            documentsDirectory = [documentsDirectory stringByAppendingPathComponent:@"images"];
        }
        if (![[NSFileManager defaultManager]fileExistsAtPath:documentsDirectory]) 
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
    }
    return self;
}

-(void)releaseCacheDic
{
    [cacheDic removeAllObjects];
}

-(NSString*)urlToFullPath:(NSString*)url
{    
    NSString *fileName = [self urlToFileName:url];
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentsDirectory = NSTemporaryDirectory();
    if (documentsDirectory!=nil) {
        documentsDirectory = [documentsDirectory stringByAppendingPathComponent:@"images"];
    }
    return [documentsDirectory stringByAppendingPathComponent:fileName];
}

-(NSString*)urlToFileName:(NSString*)url
{
    //判断后缀名
    //NSString *extension = url.pathExtension==@""?@"jpg":url.pathExtension;
    NSString *extension = @"jpg";
    if(url.pathExtension.length>0)
        extension = url.pathExtension;

    NSString *md5Name = [url MD5EncodedString];
    return  [NSString stringWithFormat:@"%@.%@",md5Name,extension];
}

-(NSData*)dataForUrl:(NSString*)url
{
    if([cacheDic objectForKey:url]!=nil)
    {
       // NSLog(@"image from cacheDic,url=%@",url);
        return [cacheDic objectForKey:url];
    }
    else 
    {
            //文件中找
        NSString *fileName = [self urlToFullPath:url];
        @synchronized(fileName)
        {
            if ([[NSFileManager defaultManager]fileExistsAtPath:fileName]) 
            {
                NSData *data = [[[NSData alloc] initWithContentsOfFile:fileName]autorelease];
                return data;
//                NSKeyedUnarchiver *unachiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//                
//                NSData *imageData = (NSData *)[unachiver decodeObjectForKey:@"image"];
//                [unachiver release];
//                [data release];
//                NSLog(@"image from local,url=%@,file=%@",url,fileName);
//                return imageData;
            }
            else 
            {
               // NSLog(@"image need to download,url=%@",url);
                return nil;
            }
        }
    }
}

-(void)setData:(NSString*)url image:(NSData*)imageData
{
    if(imageData == nil)
        return;
    
    //需要加锁
    NSString *fileName = [self urlToFullPath:url];
    @synchronized(fileName)
    {
        if ([[NSFileManager defaultManager]fileExistsAtPath:fileName]) {
            [[NSFileManager defaultManager]removeItemAtPath:fileName error:nil];
        }
        
       // NSMutableData *data = [[NSMutableData alloc] init];
//        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//        [archiver encodeObject:imageData forKey:@"image"];
//        [archiver finishEncoding];
        [imageData writeToFile:fileName atomically:YES];
//        [archiver release];
        //[data release];
    }
    [cacheDic setObject:imageData forKey:url];
    
}
-(void)dealloc
{
    [cacheDic release],cacheDic = nil;
    [super dealloc];
}
@end
